﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
using Newtonsoft.Json;

namespace weikebuluo.Common
{
    /// <summary>
    /// 提供了一个关于json的辅助类
    /// </summary>
    public class JsonOperate
    {
        #region 属性
        JavaScriptSerializer Jss = new JavaScriptSerializer(); //实例化字符串

        private string _IdField;
        private string _IdType;
        private string _TextField;
        private string _StateField;
        private string _CheckedField;
        private string _ParentIdField;
        private string _IconClsField;
        private string _AttributesField;
        private string _IconCls;
        private string _ParentId;
        private string _State;
        private string _AllData;
        private string _Checked;
        private string _Attributes;
        private DataTable _JsonTable;

        /// <summary>
        /// 数据表
        /// </summary>
        public DataTable JsonTable
        {
            set { _JsonTable = value; }
            get { return _JsonTable; }

        }
        /// <summary>
        /// ID字段名称
        /// </summary>
        public string IdField
        {
            set { _IdField = value; }
            get { return _IdField; }
        }
        /// <summary>
        /// ID类型
        /// </summary>
        public string IdType
        {
            set { _IdType = value; }
            get { return _IdType; }
        }
        /// <summary>
        /// Text字段名称
        /// </summary>
        public string TextField
        {
            set { _TextField = value; }
            get { return _TextField; }
        }
        /// <summary>
        /// State字段名称
        /// </summary>
        public string StateField
        {
            set { _StateField = value; }
            get { return _StateField; }
        }
        /// <summary>
        /// Checked字段名称
        /// </summary>
        public string CheckedField
        {
            set { _CheckedField = value; }
            get { return _CheckedField; }
        }
        /// <summary>
        /// 父ID的值
        /// </summary>
        public string ParentId
        {
            set { _ParentId = value; }
            get { return _ParentId; }
        }
        /// <summary>
        /// 父ID字段名称
        /// </summary>
        public string ParentIdField
        {
            set { _ParentIdField = value; }
            get { return _ParentIdField; }
        }
        /// <summary>
        /// 自定义属性字段名称
        /// </summary>
        public string AttributesField
        {
            set { _AttributesField = value; }
            get { return _AttributesField; }
        }
        /// <summary>
        /// 图标字段名称
        /// </summary>
        public string IconClsField
        {
            set { _IconClsField = value; }
            get { return _IconClsField; }
        }
        /// <summary>
        /// 图标名称
        /// </summary>
        public string IconCls
        {
            set { _IconCls = value; }
            get { return _IconCls; }
        }
        /// <summary>
        /// 节点自定义属性
        /// </summary>
        public string Attributes
        {
            set { _Attributes = value; }
            get { return _Attributes; }
        }
        /// <summary>
        /// 节点是否选择 true or false
        /// </summary>
        public string Checked
        {
            set { _Checked = value; }
            get { return _Checked; }
        }
        /// <summary>
        /// 节点是否打开'open' or 'closed'
        /// </summary>
        public string State
        {
            set { _State = value; }
            get { return _State; }
        }
        /// <summary>
        /// 是否添加“全部”
        /// </summary>
        public string AllData
        {
            set { _AllData = value; }
            get { return _AllData; }
        }

        #endregion

        #region DataTable转tree的Json数据
        /// <summary>
        /// DataTable转tree的Json数据
        /// </summary>
        /// <returns>tree的Json数据</returns>
        public string GetTreeJson()
        {
            List<Dictionary<string, object>> jsonList = new List<Dictionary<string, object>>();
            //查询条件
            string selectStr = "";

            if (!string.IsNullOrEmpty(this.ParentIdField))
            {
                selectStr = this.ParentIdField + " is Null";

                if (string.IsNullOrEmpty(this.IdType))
                {
                    selectStr += " or " + this.ParentIdField + "='0'";
                }
                else
                {
                    selectStr += " or " + this.ParentIdField + "=''";
                }
            }

            if (this.AllData == "true")
            {
                Dictionary<string, object> allDictionary = new Dictionary<string, object>();

                allDictionary.Add("id", "");
                allDictionary.Add("text", "全部");

                jsonList.Add(allDictionary);
            }

            //组合Json数据
            foreach (DataRow Row in this.JsonTable.Select(selectStr))
            {
                Dictionary<string, object> jsonDictionary = new Dictionary<string, object>();
                //父ID
                this.ParentId = Row[this.IdField].ToString();
                //id,text
                jsonDictionary.Add("id", Row[this.IdField].ToString());
                jsonDictionary.Add("text", Row[this.TextField].ToString());

                //节点是否打开'open' or 'closed'
                if (!string.IsNullOrEmpty(this.StateField))
                {
                    jsonDictionary.Add("state", Row[this.StateField].ToString());
                }
                else if (!string.IsNullOrEmpty(this.State))
                {
                    jsonDictionary.Add("state", this.State);
                }

                //节点是否选择 true or false
                if (!string.IsNullOrEmpty(this.CheckedField))
                {
                    jsonDictionary.Add("checked", Row[this.CheckedField].ToString());
                }
                else if (!string.IsNullOrEmpty(this.Checked))
                {
                    jsonDictionary.Add("checked", this.Checked);
                }

                //节点图标，默认"icon-folder"
                if (!string.IsNullOrEmpty(this.IconClsField))
                {
                    jsonDictionary.Add("iconCls", Row[this.IconClsField].ToString());
                }
                else if (!string.IsNullOrEmpty(this.IconCls))
                {
                    jsonDictionary.Add("iconCls", this.IconCls);
                }

                //节点自定义属性
                if (!string.IsNullOrEmpty(this.AttributesField))
                {
                    jsonDictionary.Add("attributes", Row[this.AttributesField].ToString());
                }
                else if (!string.IsNullOrEmpty(this.Attributes))
                {
                    jsonDictionary.Add("attributes", this.Attributes);
                }

                //子节点
                if (!string.IsNullOrEmpty(this.ParentIdField))
                {
                    jsonDictionary.Add("children", GetTreeChildrenJson());
                }
                //添加到总数据
                jsonList.Add(jsonDictionary);
            }

            return Jss.Serialize(jsonList);
        }

        /// <summary>
        /// DataTable转tree的Json数据
        /// </summary>
        /// <returns>tree的Json数据</returns>
        public List<Dictionary<string, object>> GetTreeChildrenJson()
        {
            List<Dictionary<string, object>> jsonList = new List<Dictionary<string, object>>();

            //查询条件
            string selectStr = this.ParentIdField + " = '" + this.ParentId + "'";

            //组合Json数据
            foreach (DataRow Row in this.JsonTable.Select(selectStr))
            {
                Dictionary<string, object> jsonDictionary = new Dictionary<string, object>();
                //父ID
                this.ParentId = Row[this.IdField].ToString();
                //id,text
                jsonDictionary.Add("id", Row[this.IdField].ToString());
                jsonDictionary.Add("text", Row[this.TextField].ToString());

                //节点是否打开'open' or 'closed'
                if (!string.IsNullOrEmpty(this.StateField))
                {
                    jsonDictionary.Add("state", Row[this.StateField].ToString());
                }
                else if (!string.IsNullOrEmpty(this.State))
                {
                    jsonDictionary.Add("state", this.State);
                }

                //节点是否选择 true or false
                if (!string.IsNullOrEmpty(this.CheckedField))
                {
                    jsonDictionary.Add("checked", Row[this.CheckedField].ToString());
                }
                else if (!string.IsNullOrEmpty(this.Checked))
                {
                    jsonDictionary.Add("checked", this.Checked);
                }

                //节点图标，默认"icon-folder"
                if (!string.IsNullOrEmpty(this.IconClsField))
                {
                    jsonDictionary.Add("iconCls", Row[this.IconClsField].ToString());
                }
                else if (!string.IsNullOrEmpty(this.IconCls))
                {
                    jsonDictionary.Add("iconCls", this.IconCls);
                }

                //节点自定义属性
                if (!string.IsNullOrEmpty(this.AttributesField))
                {
                    jsonDictionary.Add("attributes", Row[this.AttributesField].ToString());
                }
                else if (!string.IsNullOrEmpty(this.Attributes))
                {
                    jsonDictionary.Add("attributes", this.Attributes);
                }

                //子节点
                jsonDictionary.Add("children", GetTreeChildrenJson());
                //添加到总数据
                jsonList.Add(jsonDictionary);
            }

            return jsonList;
        }
        #endregion

        #region DataTable转treegrid的Json数据
        /// <summary>
        /// DataTable转treegrid的Json数据
        /// </summary>
        /// <returns>treegrid的Json数据</returns>
        public string GetTreeGridJson()
        {
            List<Dictionary<string, object>> jsonList = new List<Dictionary<string, object>>();
            //查询条件
            string selectStr = this.ParentIdField + " is Null";

            if (string.IsNullOrEmpty(this.IdType))
            {
                selectStr += " or " + this.ParentIdField + "='0'";
            }
            else
            {
                selectStr += " or " + this.ParentIdField + "=''";
            }

            //组合Json数据
            foreach (DataRow Row in this.JsonTable.Select(selectStr))
            {
                Dictionary<string, object> jsonDictionary = new Dictionary<string, object>();

                foreach (DataColumn Col in this.JsonTable.Columns)
                {
                    if (Col.DataType == System.Type.GetType("System.DateTime"))
                    {
                        string DtStr = "";

                        if (string.IsNullOrEmpty(Row[Col.ColumnName].ToString()))
                        {
                            DtStr = "";
                        }
                        else
                        {
                            DateTime Dt = Convert.ToDateTime(Row[Col.ColumnName].ToString());

                            DtStr = Dt.ToString("yyyy-MM-dd HH:mm");
                        }

                        jsonDictionary.Add(Col.ColumnName, DtStr);
                    }
                    else
                    {
                        jsonDictionary.Add(Col.ColumnName, Row[Col.ColumnName].ToString());
                    }
                }

                //父ID
                this.ParentId = Row[this.IdField].ToString();

                //节点是否打开'open' or 'closed'
                if (!string.IsNullOrEmpty(this.StateField))
                {
                    jsonDictionary.Add("state", Row[this.StateField].ToString());
                }
                else if (!string.IsNullOrEmpty(this.State))
                {
                    jsonDictionary.Add("state", this.State);
                }

                //节点是否选择 true or false
                if (!string.IsNullOrEmpty(this.CheckedField))
                {
                    jsonDictionary.Add("checked", Row[this.CheckedField].ToString());
                }
                else if (!string.IsNullOrEmpty(this.Checked))
                {
                    jsonDictionary.Add("checked", this.Checked);
                }

                //节点图标，默认"icon-folder"
                if (!string.IsNullOrEmpty(this.IconClsField))
                {
                    jsonDictionary.Add("iconCls", Row[this.IconClsField].ToString());
                }
                else if (!string.IsNullOrEmpty(this.IconCls))
                {
                    jsonDictionary.Add("iconCls", this.IconCls);
                }

                //节点自定义属性
                if (!string.IsNullOrEmpty(this.AttributesField))
                {
                    jsonDictionary.Add("attributes", Row[this.AttributesField].ToString());
                }
                else if (!string.IsNullOrEmpty(this.Attributes))
                {
                    jsonDictionary.Add("attributes", this.Attributes);
                }

                //子节点
                jsonDictionary.Add("children", GetTreeGridChildrenJson());
                //添加到总数据
                jsonList.Add(jsonDictionary);
            }

            return Jss.Serialize(jsonList);
        }

        /// <summary>
        /// DataTable转treegrid的Json数据
        /// </summary>
        /// <returns>treegrid的Json数据</returns>
        public List<Dictionary<string, object>> GetTreeGridChildrenJson()
        {
            List<Dictionary<string, object>> jsonList = new List<Dictionary<string, object>>();
            //查询条件
            string selectStr = this.ParentIdField + " = '" + this.ParentId + "'";

            //组合Json数据
            foreach (DataRow Row in this.JsonTable.Select(selectStr))
            {
                Dictionary<string, object> jsonDictionary = new Dictionary<string, object>();

                foreach (DataColumn Col in this.JsonTable.Columns)
                {
                    if (Col.DataType == System.Type.GetType("System.DateTime"))
                    {
                        string DtStr = "";

                        if (string.IsNullOrEmpty(Row[Col.ColumnName].ToString()))
                        {
                            DtStr = "";
                        }
                        else
                        {
                            DateTime Dt = Convert.ToDateTime(Row[Col.ColumnName].ToString());

                            DtStr = Dt.ToString("yyyy-MM-dd HH:mm");
                        }

                        jsonDictionary.Add(Col.ColumnName, DtStr);
                    }
                    else
                    {
                        jsonDictionary.Add(Col.ColumnName, Row[Col.ColumnName].ToString());
                    }

                }

                //父ID
                this.ParentId = Row[this.IdField].ToString();

                //节点是否打开'open' or 'closed'
                if (!string.IsNullOrEmpty(this.StateField))
                {
                    jsonDictionary.Add("state", Row[this.StateField].ToString());
                }
                else if (!string.IsNullOrEmpty(this.State))
                {
                    jsonDictionary.Add("state", this.State);
                }

                //节点是否选择 true or false
                if (!string.IsNullOrEmpty(this.CheckedField))
                {
                    jsonDictionary.Add("checked", Row[this.CheckedField].ToString());
                }
                else if (!string.IsNullOrEmpty(this.Checked))
                {
                    jsonDictionary.Add("checked", this.Checked);
                }

                //节点图标，默认"icon-folder"
                if (!string.IsNullOrEmpty(this.IconClsField))
                {
                    jsonDictionary.Add("iconCls", Row[this.IconClsField].ToString());
                }
                else if (!string.IsNullOrEmpty(this.IconCls))
                {
                    jsonDictionary.Add("iconCls", this.IconCls);
                }

                //节点自定义属性
                if (!string.IsNullOrEmpty(this.AttributesField))
                {
                    jsonDictionary.Add("attributes", Row[this.AttributesField].ToString());
                }
                else if (!string.IsNullOrEmpty(this.Attributes))
                {
                    jsonDictionary.Add("attributes", this.Attributes);
                }

                //子节点
                jsonDictionary.Add("children", GetTreeGridChildrenJson());
                //添加到总数据
                jsonList.Add(jsonDictionary);
            }

            return jsonList;
        }
        #endregion

        #region DataTable转datagrid的Json字符串

        /// <summary>
        /// DataTable转datagrid的Json字符串
        /// </summary>
        /// <param name="JsonTable">数据表</param>
        /// <returns>
        /// datagrid的Json字符串
        /// </returns>
        public string GetDataGridJson(DataTable JsonTable)
        {
            return "{ \"total\":" + JsonTable.Rows.Count.ToString() + ",\"rows\":" + TableToBasicJson(JsonTable) + "}";
        }

        /// <summary>
        /// DataTable转datagrid的Json字符串
        /// </summary>
        /// <param name="JsonTable">数据表</param>
        /// <param name="strCount">记录数</param>
        /// <returns>datagrid的Json字符串</returns>
        public string GetDataGridJson(DataTable JsonTable, string strCount)
        {
            return "{ \"total\":" + strCount + ",\"rows\":" + TableToBasicJson(JsonTable) + "}";
        }

        /// <summary>
        /// DataTable转datagrid的Json字符串
        /// </summary>
        /// <param name="JsonTable">数据表</param>
        /// <param name="strCount">记录数</param>
        /// <returns>datagrid的Json字符串</returns>
        public string GetDataGridJson(DataTable JsonTable, int count)
        {
            return "{ \"total\":" + count + ",\"rows\":" + TableToBasicJson(JsonTable) + "}";
        }


        public string GetDataGridJson(DataTable JsonTable, DataTable strCount, DataTable FooterTable)
        {
            return "{ \"total\":" + strCount + ",\"rows\":" + TableToBasicJson(JsonTable) + ",\"footer\":" + TableToBasicJson(FooterTable) + "}";
        }
        #endregion

        #region DataTable转Json
        /// <summary>
        /// DataTable转Json
        /// </summary>
        /// <param name="JsonTable">数据表</param>
        /// <returns>Json字符串</returns>
        public string TableToBasicJson(DataTable JsonTable)
        {
            //组合Json数据
            List<Dictionary<string, object>> JsonList = new List<Dictionary<string, object>>();
            foreach (DataRow Row in JsonTable.Rows)
            {
                Dictionary<string, object> JsonDrow = new Dictionary<string, object>();

                foreach (DataColumn Col in JsonTable.Columns)
                {
                    if (Col.DataType == System.Type.GetType("System.DateTime"))
                    {
                        string DtStr = "";

                        if (string.IsNullOrEmpty(Row[Col.ColumnName].ToString()))
                        {
                            DtStr = "";
                        }
                        else
                        {
                            DateTime Dt = Convert.ToDateTime(Row[Col.ColumnName].ToString());

                            DtStr = Dt.ToString("yyyy-MM-dd HH:mm");
                        }

                        JsonDrow.Add(Col.ColumnName, DtStr);
                    }
                    else
                    {
                        JsonDrow.Add(Col.ColumnName, Row[Col.ColumnName].ToString());
                    }
                }

                JsonList.Add(JsonDrow);
            }

            return Jss.Serialize(JsonList);
        }
        #endregion

        #region Json转DataTable
        /// <summary> 
        /// Json转DataTable 
        /// </summary> 
        /// <param name="json">Json字符串</param> 
        /// <returns>数据表</returns> 
        public DataTable JsonToTable(string JsonString)
        {
            List<Dictionary<string, object>> JsonList = new List<Dictionary<string, object>>();

            JsonList = Jss.Deserialize<List<Dictionary<string, object>>>(JsonString);

            DataTable JsonTable = new DataTable();

            if (JsonList.Count > 0)
            {
                foreach (Dictionary<string, object> JsonDrow in JsonList)
                {
                    if (JsonTable.Columns.Count == 0)
                    {
                        foreach (string Key in JsonDrow.Keys)
                        {
                            JsonTable.Columns.Add(Key, JsonDrow[Key].GetType());
                        }
                    }

                    DataRow JsonRow = JsonTable.NewRow();

                    foreach (string Key in JsonDrow.Keys)
                    {
                        JsonRow[Key] = JsonDrow[Key];
                    }

                    JsonTable.Rows.Add(JsonRow);
                }
            }

            return JsonTable;
        }
        #endregion

        #region 其它
        /// <summary>
        /// 类对像转换成json格式
        /// </summary> 
        /// <returns></returns>
        public static string ToJson(object t)
        {
            return JsonConvert.SerializeObject(t, Formatting.Indented,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Include });
        }
        /// <summary>
        /// 类对像转换成json格式
        /// </summary>
        /// <param name="t"></param>
        /// <param name="HasNullIgnore">是否忽略NULL值</param>
        /// <returns></returns>
        public static string ToJson(object t, bool HasNullIgnore)
        {
            if (HasNullIgnore)
                return JsonConvert.SerializeObject(t, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
            else
                return ToJson(t);
        }
        /// <summary>
        /// json格式转换
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="strJson"></param>
        /// <returns></returns>
        public static T FromJson<T>(string strJson) where T : class
        {
            if (!string.IsNullOrEmpty(strJson))
                return JsonConvert.DeserializeObject<T>(strJson);
            return null;
        }
        #endregion
    }
}
